const CryptoJS = require('./crypto-js')
const NodeRSA = require('./node-rsa/src/NodeRSA')
const fs = require('fs')

//解密方法 ECB
// xx.js filePath output
function DecryptECB() {
  try {
    var args = process.argv.slice(2)
    const filePath = args[0]
    const output = args[1]
    const key = args[2]
    const version = args[3]
    const privateKey = args[4]
    const encryptoedFileStr = fs.readFileSync(filePath, 'utf-8') // 加密的字符串
    const pat = /^(.*){{{(.*)}}}\[\[(.*)\]\](\(\(\((.*)\)\)\))?$/g
    const match = pat.exec(encryptoedFileStr)
    // 解密文件
    if (match) {
      let encryptoedStr = match[1]
      const rsakey = match[2] // 对称加密的秘钥 需要对比解密后与key是否一致
      const fileVersion = match[3]
      console.log(fileVersion, version)
      const checkFileVersion = checkVersion(fileVersion, version)
      if (!checkFileVersion) {
        console.log('版本不匹配')
        return { type: 'exit', message: '版本不匹配', success: false }
      }

      // 注释  修改 解密不对比，直接解密，解密失败密码错误
      // const checkPswRes = checkPsw(key, rsakey, privateKey)
      // if (!checkPswRes) {
      //   console.log('密码不一致')
      //   return { type: 'exit', message: '密码不一致！', success: false }
      // }
      // 使用散列密码 解密文件
      const paramsKEY = CryptoJS.enc.Utf8.parse(key)

      let results = []
      console.log('解密1 字符串长度:' + encryptoedStr.length)
      let totalArr = encryptoedStr.split('|||')
      const lengths = totalArr.length
      console.log('解密2 加密文件长度：' + lengths)
      for (let i = 0; i < lengths - 1; i++) {
        // const encryptedHexStr = CryptoJS.enc.Hex.parse(totalArr[0])
        // const srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr)
        const decrypt = CryptoJS.AES.decrypt(totalArr[0], paramsKEY, {
          mode: CryptoJS.mode.ECB,
          padding: CryptoJS.pad.Pkcs7,
        })
        const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8)
        results.push(decryptedStr)
        totalArr = totalArr.slice(1)

        console.log(`progress:${((i / lengths) * 100).toFixed(0)}:${i === 0 ? 'start' : 'ing'}`)
      }

      console.log('解密3 totalArr', totalArr)
      const exists = fs.existsSync(output)
      console.log(output, exists)
      if (!exists) {
        fs.mkdir(output.replace('zb_decryptoed.json', ''), (err) => {
          if (err) {
            console.log('创建目录失败')
            return { type: 'mkdir', message: '创建目录失败', success: false }
          }
          return { type: 'mkdir', message: '', success: true }
        })
      }
      console.log('解密5' + output)
      fs.writeFileSync(output, results.join(''), 'utf-8')

      // 如果存在工程量清单
      if (match[4] && match[5]) {
        fs.writeFileSync(output.replace('zb_decryptoed.json', 'bill.json'), match[5], 'utf-8')
      }
      console.log('progress:100:done')
    }
  } catch (err) {
    console.log('解密出错')
  }
}

function checkVersion(fileV, appV) {
  const fileVersionArr = fileV.split('.')
  const appVersionArr = appV.split('.')
  // if (fileVersionArr[0] !== appVersionArr[0] || fileVersionArr[1] !== appVersionArr[1]) {
  //   return false
  // }
  if (
    Math.abs(+fileVersionArr[0] - +appVersionArr[0] == 1) ||
    Math.abs(+fileVersionArr[1] - +appVersionArr[1] == 1)
  ) {
    return false
  }
  return true
}

/**
 * RSA 解密密
 * @param privateKey 私钥
 * @param data 待加密数据
 * @returns {PromiseLike<ArrayBuffer>} 返回解密字符串
 */
function decrypt(privateKey, data) {
  try {
    const key = new NodeRSA(privateKey, 'pkcs8-private')
    key.setOptions({
      encryptionScheme: 'pkcs1_oaep',
    })
    const result = key.decrypt(data, 'utf8')
    console.log('decrypt rsa:', result)
    return result
  } catch (err) {
    console.error('RSA解密error:', err)
    return ''
  }
}

// 检查密码是否一致
function checkPsw(key, rasKey, privateKey) {
  const deKey = decrypt(privateKey, rasKey)
  console.log(key, deKey)
  if (deKey === key) {
    return true
  }
  return false
}

DecryptECB()
